﻿
function NemoFilter(holder) {
    if (!holder) return;
    this.UI = new Object();
    this.UI.Holder = $(holder);
    this.RowSelector = this.UI.Holder.attr('data-rowselector');
    this.ValueSelector = this.UI.Holder.attr('data-rowvalueselector');

    this.Rows = new Array();
    var filter = this;
    $(this.RowSelector).each(function () {
        var r = new NemoFilterRow(filter, this, filter.ValueSelector);
        filter.Rows.push(r);
    });
    this.UI.Holder.data('nemofilter', this).keydown(function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    }).keyup(function (event) {
        $(this).data('nemofilter').Filter($(this).val(), event);
    });
};

NemoFilter.prototype.Filter = function (filterPhase, e) {
    filterPhase = filterPhase.toLowerCase();
    for (var xr = 0; xr < this.Rows.length; xr++) {
        this.Rows[xr].DetermineIsMatchRow(filterPhase);
    }
};

NemoFilter.prototype.Init = function () {
    $('input[data-type=filter]').each(function () {
        var nf = new NemoFilter($(this));
    });
};

function NemoFilterRow(filter, row, valueSelector) {
    this.Filter = filter;
    this.UI = new Object();
    this.UI.Holder = $(row);
    this.Value = this.UI.Holder.find(valueSelector).text().toLowerCase();
    this.IsVisible = true;
};

NemoFilterRow.prototype.DetermineIsMatchRow = function (searchPhase) {
    var visible = this.Value.indexOf(searchPhase) !== -1;
    if (visible !== this.Visible) {
        this.Visible = visible;
        if (this.Visible)
            this.UI.Holder.show();
        else
            this.UI.Holder.hide();
    }
};
var tableFilter = new NemoFilter();
window.Nemo.RegisterController(tableFilter);
window.Nemo.TableFilter = tableFilter;